<template>
	<view>
		<map
			id="myMap"
			show-location
			:latitude="myPos.latitude"
			:longitude="myPos.longitude"
			:markers="covers"
			:scale="16"
			style="width: 100vw;height: 100vh;"
			@markertap="handleMarkertap"
			@labeltap="handleMarkertap"
			@regionchange="handleRegionchange"
			@tap="showInfoWindow = false"
			@updated="handleMapUpdated"
		></map>
		<view class="info-window" v-if="showInfoWindow">
			<view class="site-item">
				<view class="title u-f-jsb">
					<view class="title-l">
						<view>{{ site.siteName }}</view>
						<view>{{ site.siteAddress }}</view>
					</view>
					<view class="title-r" @tap="openMapapp">
						<view>
							<u-icon name="map"></u-icon>
							<text>{{ site.distance }}km</text>
						</view>
						<view>开始导航</view>
					</view>
				</view>
				<view class="bucket-list">
					<view
						class="bucket u-f-jsb"
						v-for="bucket in site.machineOrBucket"
						:key="bucket.id"
					>
						<view class="bucket-l">
							<view class="name">{{ bucket.bucketOrMachineName || bucket.bucketName }}</view>
							<view>编号：{{ bucket.deviceName || bucket.macCode }}</view>
							<view class="info"> 
								<text>
									桶容量：{{
										(bucket.totalCapacity || bucket.totalWeight) | kg2ton
									}}吨
								</text>
								<text>
									余量：
									<text
										:class="{
											red: (bucket.actualRestWeight / bucket.totalWeight) < 0.2
										}"
									>
										{{
											(bucket.currentCapacity || bucket.actualRestWeight)| kg2ton
										}}
									</text>
									吨
								</text>
								<text>
									传感器余量：{{ (bucket.iotRestWeight | kg2ton) || '---' }}吨
								</text>
							</view>
						</view>
						<view class="btn-supply" @tap="jump(bucket)">补液</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import siteCard from '@/components/site-card/site-card.vue';
import { mapDistance, convert2TecentMap } from '@/common/utils.js';
export default {
	components: { siteCard },
	data() {
		return {
			covers: [],
			northeast: '',
			southwest: '',
			sitesMap: {},
			showInfoWindow: false,
			site: {}
		};
	},
	computed: {
		myPos() {
			return this.$store.state.myPos;
		}
	},
	onLoad(options) {
		uni.showLoading({
			mask:true
		})
		if (options.site) {
			const site = JSON.parse(decodeURIComponent(options.site));
			this.siteId = site.id;
			this.site = site;
		}
	},
	onReady() {
		this.mapContext = uni.createMapContext('myMap', this);
		const { siteLat, siteLng } = this.site;
		
		if(siteLat && siteLng) {
			this.mapContext.moveToLocation({
				longitude: siteLng,
				latitude: siteLat
			});
		}
		this.mapContext.getRegion({
			success: e => {
				this.northeast = e.northeast;
				this.southwest = e.southwest;
				this.getMapSites();
			}
		});
	},
	onShow() {
		if (this.siteId && this.sitesMap[this.siteId]) {
			this.getSiteDetail(this.siteId);
		}
	},
	methods: {
		// 设置覆盖物
		setCovers() {
			let tempArr = [];
			for (let siteId in this.sitesMap) {
				let site = this.sitesMap[siteId];
				let flag1 =
					this.southwest.longitude <= site.siteLng &&
					this.northeast.longitude >= site.siteLng;
				console.log(this.southwest.longitude, site.siteLng, this.northeast.longitude);
				let flag2 =
					this.southwest.latitude <= site.siteLat &&
					this.northeast.latitude >= site.siteLat;

				if (flag1 && flag2 && !site.isRender) {
					let color = site.percentage < site.warningThreshold ? '#ff0000' : '#00aaff';
					var obj = {
						id: Number(siteId),
						latitude: site.siteLat,
						longitude: site.siteLng,
						width: 60,
						height: 60,
						label: {
							id: Number(siteId),
							content: parseInt(site.percentage * 100) + '%',
							color: '#ffffff',
							anchorX: -10,
							anchorY: -36,
							borderRadius: 50,
							padding: 15,
							bgColor: color,
							borderColor: '#ffffff',
							borderWidth: 2
						}
					};
					tempArr.push(obj);
					site.isRender = true;
				}
			}
			if (!this.covers.length) {
				this.covers = [...tempArr];
			} else {
				this.addMarkers(tempArr);
			}
		},
		handleMapUpdated() {
			uni.hideLoading();
		},
		// 地图视野移动事件
		handleRegionchange(e) {
			console.log(e);
			// this.showInfoWindow = false;
			if (e.type === 'begin') return;
			const { northeast, southwest } = e.detail.region;
			this.northeast = northeast;
			this.southwest = southwest;
			this.setCovers();
		},
		// 标记物点击
		handleMarkertap(e) {
			console.log(e);
			const { markerId } = e.detail;
			this.getSiteDetail(markerId);
		},
		// 打开第三方地图导航
		openMapapp() {
			this.mapContext.openMapApp({
				latitude: this.site.siteLat,
				longitude: this.site.siteLng,
				destination: this.site.siteAddress // 目的地名称
			});
		},
		getMapSites() {
			this.$u.api._getMapSite().then(res => {
				console.log(res);
				res.reList.forEach(item => {
					item.isRender = false;
					// 百度坐标转 gcj02 坐标；
					item = convert2TecentMap(item);
					this.sitesMap[item.siteId] = item;
				});
				// 如果从首页进来并且已经携带siteId;
				if (this.siteId) {
					console.log('开始显示');
					this.getSiteDetail(this.siteId);
				}
				// 设置覆盖物
				this.setCovers();
			});
		},
		getSiteDetail(siteId) {
			this.siteId = siteId;
			this.$u.api._getBucketInfo({ siteId: siteId }).then(res => {
				this.showInfoWindow = true;
				let site = { ...this.sitesMap[siteId] };
				console.log('site', site);
				// 计算距离 mapDistance
				const { latitude, longitude } = this.myPos;
				const distance = mapDistance(latitude, longitude, site.siteLat, site.siteLng);
				this.site = {
					...site,
					distance,
					siteId,
					machineOrBucket: [...res.bucket]
				};
			});
		},
		jump(bucket) {
			console.log(bucket);
			bucket.siteId = this.site.siteId;
			bucket.siteName = this.site.siteName;
			bucket.bucketOrMachineName = bucket.bucketName || bucket.macName;
			if (bucket.deviceName) {
				uni.navigateTo({
					url:
						`/pages/supplying/supplying?site=` +
						encodeURIComponent(JSON.stringify(bucket))
				});
			} else {
				uni.navigateTo({
					url:
						`/pages/supplying/noSensor?site=` +
						encodeURIComponent(JSON.stringify(bucket))
				});
			}
		},
		addMarkers(markers) {
			this.mapContext.addMarkers({
				clear: false,
				markers
			});
		}
	}
};
</script>

<style lang="scss">
.info-window {
	position: fixed;
	min-height: 300rpx;
	width: 96vw;
	bottom: 60rpx;
	left: 2vw;
	bottom: calc(60rpx + constant(safe-area-inset-bottom));
	bottom: calc(60rpx + env(safe-area-inset-bottom));
}
.site-item {
	border-radius: 16rpx;
	background-color: #ffffff;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 0 6px 1rpx rgba(0, 0, 0, 0.1);

	.title {
		border-bottom: 1rpx solid #eee;
		padding-bottom: 10rpx;
		.title-l {
			flex: 1;
			flex-shrink: 0;
			overflow: hidden;
			& > view:nth-child(1) {
				font-weight: 800;
				font-size: 32rpx;
				margin-bottom: 10rpx;
			}
			& > view:nth-child(2) {
				font-size: 28rpx;
				color: #808080;
			}
		}
		.title-r {
			width: 200rpx;
			font-weight: 600;
			color: $uni-color-primary;
			display: flex;
			flex-direction: column;
			align-items: flex-end;
		}
	}
	.bucket-list {
		max-height: 600rpx;
		overflow-y: scroll;
		.bucket {
			padding: 10rpx 0;
			padding-bottom: 20rpx;
			.bucket-l {
				flex: 1;
				flex-shrink: 0;
				overflow: hidden;
				margin-right: 10rpx;
				.name {
					color: #333333;
					font-size: 32rpx;
					margin-bottom: 10rpx;
					font-weight: 600;
				}
				.info text {
					font-size: 28rpx;
					margin-right: 20rpx;
					color: #808080;

					.red {
						color: red;
					}
				}
			}
			.btn-supply {
				align-self: flex-end;
				width: 120rpx;
				height: 50rpx;
				line-height: 50rpx;
				border-radius: 25rpx;
				text-align: center;
				background-color: $uni-color-primary;
				color: #ffffff;
			}
		}
	}
}
</style>
